package deptlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DelDeptLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	getDeptListLogic     *GetDeptListLogic
	getDeptSonByPidLogic *GetDeptSonByPidLogic
}

func NewDelDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelDeptLogic {
	return &DelDeptLogic{
		ctx:                  ctx,
		svcCtx:               svcCtx,
		Logger:               logx.WithContext(ctx),
		getDeptListLogic:     NewGetDeptListLogic(ctx, svcCtx),
		getDeptSonByPidLogic: NewGetDeptSonByPidLogic(ctx, svcCtx),
	}
}

func (l *DelDeptLogic) DelDept(in *syspb.DelDeptReq) (*syspb.DelDeptResp, error) {
	if in.GetId() == 0 || (!in.GetIsDel() && in.GetUpdateUser() == "") {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除部门失败：参数缺失"),
			tool.GetErrMsgFormat("delete dept"), "params is not existed", in)
	}

	// 查询出该部门的所有子类
	deptListResp, err := l.getDeptListLogic.GetDeptList(&syspb.GetDeptListReq{})
	if err != nil {
		return nil, err
	}
	list := deptListResp.GetList()

	// 子类数据
	var children []*syspb.SysDept
	if len(list) > 0 {
		deptSonListResp, _ := l.getDeptSonByPidLogic.GetDeptSonByPid(&syspb.GetDeptSonByPidReq{
			Pid:  in.GetId(),
			List: list,
		})
		children = deptSonListResp.GetList()
	}

	// 存在下级部门，不允许删除
	if len(children) > 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除部门失败：存在下级部门，不允许删除"),
			tool.GetErrMsgFormat("delete dept"), "dept children is existed", in)
	}

	// 部门存在用户，不允许删除
	// 不能直接调用user包里的逻辑，避免循环依赖
	count, err := l.svcCtx.SysDeptModel.FindCount(l.ctx, l.svcCtx.SysUserModel.CountBuilder("1").
		Where(squirrel.Eq{"dept_id": in.GetId()}))
	if err != nil || count > 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除部门失败：部门存在用户，不允许删除"),
			tool.GetErrMsgFormat("delete dept"), "dept user is existed", in)
	}

	// 处理删除
	err = l.svcCtx.SysDeptModel.DeleteEx(l.ctx, nil, []int64{in.GetId()}, in.GetIsDel(), in.GetUpdateUser())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("delete dept"), err, in)
	}

	return &syspb.DelDeptResp{}, nil
}
